package com.jswlw.web.fitler;

import com.alibaba.fastjson.JSON;
import com.jswlw.common.Constants;
import com.jswlw.common.ResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常拦截器
 * @create 2017-11-03 9:10
 */
public class ExceptionFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);

    private String errorPage;//跳转的错误信息页面

    //初始化读取你配置的提示页面路径
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //读取错误信息提示页面路径
        errorPage = filterConfig.getInitParameter("errorPage");
        if (null == errorPage || "".equals(errorPage)) {
            throw new RuntimeException("没有配置错误信息跳转页面,请再web.xml中进行配置\n<init-param>\n<param-name>errorPage</param-name>\n<param-value>/error.jsp</param-value>\n </init-param>\n路径可以是你自己设定的任何有效路径页面！！");
            //System.out.println("没有配置错误信息跳转页面");
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        //捕获你抛出的业务异常
        try {
            filterChain.doFilter(request, response);
        }  catch (Exception e) {
            logger.error(e.getMessage(), e);
            this.constructResult(response, request, ResponseStatus.SYS_ERROR);
        }
    }

    private void constructResult(
            HttpServletResponse response,
            HttpServletRequest request,
            ResponseStatus responseStatus) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.toLowerCase().endsWith(".shtml")
                || uri.toLowerCase().equals("/")
                ) {
            request.getRequestDispatcher(errorPage).forward(request, response);
            //跳转到信息提示页面！！
        } else {
            //构造返回值
            ModelMap responseData = new ModelMap();
            responseData.put(Constants.RESULT, responseStatus.getCode());
            responseData.put(Constants.MESSAGE, responseStatus.getMsg());

            //构造response对象
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.append(JSON.toJSONString(responseData));
            } catch (IOException ioe) {
                logger.error(ioe.getMessage());
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}